#!/usr/bin/env python
from lib.format_time import *
from lib.HandleMysql import *
from lib.handle_mongo import *
from lib.switch_code import *
from zhineng_conn import *
from config_tools import *
from lib.load_data import *
import time
import math
import sys
import re
reload(sys)
sys.setdefaultencoding('utf-8')


#mysql - top
def set_top_conn():    
    conn = HandleMysql('topinfo-s.db.58dns.org','58885','topolr58user',"qy#u$#3sfuHn$qJe",'dbwww58com_topinfo')
    conn.connect()
    return conn
def format_timestamp(ts):
    ts += 1262304000
    return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(ts))

def execute(date):
    stat_conn = set_58_conn()
    top_conn = set_top_conn()
    dict_conn = set_dict_conn()
    line_list = []
    stat_table='top_info_catetime'

    query = "select configid,timetype,cateid,timelength,effid,failid,addtime from topinfo_catetime"
    items = top_conn.get_results(query)
    for item in items:
        config_id = item[0]
        time_type = item[1]
        cate_id = item[2]
        time_length = item[3]
        eff_id = item[4]
        fail_id = item[5]
        add_time = item[6]
        
        eff_time = format_timestamp(eff_id)
        fail_time = format_timestamp(fail_id)
        
        arr = time_length.split('|')
        tl = arr[0]
        
        min_hour = '0'
        if tl.find('d') > 0:
            min_hour = 24 * int(tl.replace('d',''))
        else:
            min_hour = tl.replace('h','')
        
        channel_id = 0;
        q = "select channel_id from cate_channel where channel_id in (1000009,1000419) and cate_id=%s"%cate_id
        its = dict_conn.get_results(q)
        if len(its) > 0:
            its = its[0][0]
        
        cate_rate = 0.9;
        q = "select rate,factor from top_info_price_rate where channel_id=%s and hours=%s"%(channel_id,min_hour)
        its = stat_conn.get_results(q)
        if len(its) > 0 :
            rate = its[0][0]
            factor = its[0][1]
            
            cate_rate = rate * factor
        
        param = [config_id,time_type,cate_id,time_length,eff_time,fail_time,add_time,min_hour,cate_rate]
        #print param
        line_list.append('\t'.join(map(lambda i : str(i), param)))

        
    cont = '\n'.join(line_list)
    path = "/work3/opt/analytic/lh_tmp_data/top_info/catetime/"
    file_name = "top_info_catetime_%s.txt"%date.replace('-',"")
    writeTextToFile(path,file_name,"w",cont)
    q = "truncate table %s"%stat_table
    stat_conn.execute_sql(q)
    #print cont
    load_data(stat_conn,path+file_name,stat_table,'\t')
    
    stat_conn.close()
    top_conn.close()
    dict_conn.close()

def main():

   #date = '2012-05-28'
   #execute(date)   
   if len(sys.argv)==1:
        start_date=get_yesterday()
        end_date=start_date
   elif len(sys.argv)==2:
        start_date=format_date(sys.argv[1])
        end_date=start_date
   elif len(sys.argv)==3:
        start_date=format_date(sys.argv[1])
        end_date=format_date(sys.argv[2])
   stat_date=start_date
   while stat_date>=start_date and stat_date<=end_date:
        print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
        #
        execute( stat_date) 
        print "The program of the date of %s is end at %s " %(stat_date,get_now())
        stat_date=var_date(stat_date)


if __name__=='__main__':
    main()
